<!--  项目在线评审列表 -->
<template>
  <RkContainer :isFooter="false"
    :isAside=false>
    <template #header_left>
      <RkButtonGroup v-if="query.nodeId=='node_9'"
        :options="json_online_button"
        v-model="queryParams.wfStatus"
        @click="handleSearch" />
      <RkButtonGroup v-if="query.nodeId=='node_10'"
        :options="json_confirm_button"
        v-model="queryParams.wfStatus"
        @click="handleSearch" />
    </template>
    <template #header_right>
      <el-button v-if="query.nodeId=='node_10' && queryParams.wfStatus=='001'"
        type="primary"
        @click="handleOperation('confirm', '确认')">确认</el-button>
    </template>
    <template #main>
      <RkCenter>
        <template #content>
          <rk-grid ref="grProjApply"
            :title="title"
            dataUrl="/onlineReview/proApplyOnlineReview"
            :boxConfig="(query.nodeId=='node_10')"
            :params="queryParams"
            :columns="tableColumns">
            <template #toolbar_title_buttons>
              <el-input v-model="queryParams.mhcx"
                placeholder="请输入项目名称/编码"
                class="mr-15px w-200px"
                @input="handleSearch"
                clearable>
              </el-input>
            </template>
            <template #lodeFile="{ row }">
              <div class="operation-box">
                <el-button v-if="showLodeFile"
                  link
                  type="primary"
                  @click.stop="handleOptation(row,'preview')">预览</el-button>
                <el-button v-if="showLodeFile"
                  link
                  type="primary"
                  @click.stop="handleOptation(row,'downLoad')">下载</el-button>
                <span v-if="!showLodeFile">-</span>
              </div>
            </template>
            <template #operation="{ row }">
              <el-button v-if="query.nodeId=='node_9' && queryParams.wfStatus=='001'"
                type="primary"
                size="small"
                @click="handleOpenRecord(1,row)">评审</el-button>
              <el-button v-if="query.nodeId=='node_9' && queryParams.wfStatus=='002'"
                type="primary"
                size="small"
                @click="handleOpenRecord(2,row)">修改</el-button>
            </template>
          </rk-grid>
        </template>
      </RkCenter>
    </template>
    <ExpertRatingEdit ref="expertRatingEditRef"
      :proIds="proId"
      :operatorType="operatorType"
      :projectItem="projectItem"
      @refresh="handleSearch" />
  </RkContainer>
</template>
<script setup>
import { ElMessage, ElLoading } from 'element-plus'
import { json_online_button, json_confirm_button } from '@/common/button-data.js'
import { COMMON_BOND_TYPES } from '@/enums/enums-common.js'
import { WF_TASK_AUDIT } from '@/common/cons-common.js'
import { useUserStore } from '@/stores/modules';
import ExpertRatingEdit from './drawer/ExpertRatingEdit.vue'
import { reactive } from 'vue'
import { previewFile, fileType, dowloadFile, openNewWindow } from '@/utils/file-utils.js';
import { useFilesZjpsApi, useProjectApi } from '@/api/index'
const { onlineReviewData, downloadReportData } = useFilesZjpsApi();
const { reserveProHandleTask } = useProjectApi();
// ----- pinia
const userInfo = useUserStore().userInfo
const title = ref('');
// ----- 路由相关操作
// const query = route.query

//测试数据
let query = {
  nodeId: "node_9",
  processKey: "PRO_CBK_ZJPS"
}
if (query.nodeId == 'node_9') {
  title.value = '项目专家评审'
} else {
  title.value = '项目评审确认'
}
// ----- 表格相关操作
// 表格查询参数
const queryParams = reactive({
  mhcx: undefined,
  status: undefined,
  nodeId: query.nodeId,
  wfStatus: history.state.wfStatus ?? '001',
  processKey: query.processKey
})
let showLodeFile = ref(false)
let showOperation = ref(false)
watch(() => queryParams.wfStatus, (newValue) => {
  if (newValue == '001') {
    showLodeFile.value = queryParams.nodeId == 'node_9' ? false : true
    showOperation.value = queryParams.nodeId == 'node_9' ? true : false
  } else if (newValue == '008') {
    showLodeFile.value = true
    showOperation.value = false
  } else {
    showLodeFile.value = true
    showOperation.value = queryParams.nodeId == 'node_9' ? true : false
  }
}, { deep: true, immediate: true })

//评审页面
const expertRatingEditRef = ref(null)
const grProjApply = ref('')

const tableColumns = ref([
  { field: 'adName', title: '地区', width: 150 },
  { field: 'agencyName', title: '单位', width: 200 },
  { field: 'proCode', title: '项目编码', width: 200 },
  { field: 'proName', title: '项目名称', width: 200, cellRender: { name: 'xmYHS' } },
  { field: 'fundInvestAreaName', title: '项目投向领域', width: 200 },
  { field: 'proTypeName', title: '项目类型', width: 150 },
  { field: 'lodeFile', title: '评审报告', width: 150, showOverflow: true, align: 'center', slots: { default: 'lodeFile' } },
  { field: 'remark', title: '备注', width: 150 },
  { field: 'operation', title: '操作', fixed: 'right', visible: showOperation, width: 100, showOverflow: true, align: 'center', slots: { default: 'operation' } }
])

/**查询 */
const handleSearch = () => {
  grProjApply.value.searchEvent()
}
//送审、撤销送审、删除
const handleOperation = async (buttonType, textName) => {
  const seleRows = grProjApply.value.getCheckboxRecords()
  if (seleRows.length == 0 || !seleRows) {
    ElMessage({ message: `请至少选择一条数据进行${textName}！`, type: "warning" });
    return;
  }
  //获取选中数据
  const ProId = []
  const TaskId = []
  const ApplyId = []
  seleRows.forEach(element => {
    ApplyId.push(element.applyId)
    ProId.push(element.proId)
    TaskId.push(element.taskId)
  });
  const applyIds = ApplyId.join(',')
  const proIds = ProId.join(',')
  const taskIds = TaskId.join(',')
  if (buttonType == 'confirm') { //确认
    const deleteParams = { applyIds, taskIds, proIds, nodeId: queryParams.nodeId, taskType: WF_TASK_AUDIT.value }
    const result = await reserveProHandleTask(deleteParams)
    const { data, code, msg } = result
    if (code === 200) {
      ElMessage({ message: `${textName}成功！`, type: "success" });
      handleSearch()
    } else {
      ElMessage({ message: `${msg}`, type: "error" });
    }
  }
}

/**表格点击方法 */
const handleOptation = async (row, type) => {
  const { reviewTaskId, applyId, expertId, } = row
  let params = {
    taskId: reviewTaskId,
    applyId,
    expertId
  }
  const loading = ElLoading.service({
    lock: true,
    text: '加载中...',
  })
  if (type === 'preview') {
    let result = await onlineReviewData(params)
    const code = result?.code
    const msg = result?.message
    if (code) {
      ElMessage({ message: msg ?? '业务失败！', type: "error" });
      loading.close()
    } else {
      if (result) {
        let url = null
        loading.close()
        url = await previewFile(result, fileType.pdf)
        openNewWindow(url, '项目评审报告')
      } else {
        loading.close()
        ElMessage({ message: '没有任何数据！', type: "warning" });
      }
    }
  } else if (type === 'downLoad') {
    ElMessage({ message: '文件正在下载，请稍后！', type: "info" })
    const result = await downloadReportData(params)
    const code = result?.code
    const msg = result?.message
    if (code) {
      loading.close()
      ElMessage({ message: msg ?? '业务失败！', type: "error" });
    } else {
      if (result) {
        loading.close()
        dowloadFile(result, '项目评审报告', fileType.pdf)
      } else {
        loading.close()
        ElMessage({ message: '没有任何数据！', type: "warning" });
      }
    }
  }
}

let projectItem = reactive({})
let operatorType = ref(null)
let proId = ref('')
const handleOpenRecord = (type, row) => {
  //修改
  operatorType.value = type
  projectItem.value = row
  proId.value = row.proId
  expertRatingEditRef.value.handleOpen();
}
</script>

<style lang="scss" scoped>
.mr-15px {
	margin-right: 15px;
	&:last-child {
		margin-right: 0;
	}
}
.w-200px {
	width: 200px;
}
</style>